package top.whysu.edevice.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.whysu.edevice.dto.emqx.MqttBaseRequest;


/**
 * 设备接入处理工具类
 */
public class DeviceJoinUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(DeviceJoinUtil.class);

    /**
     * 设备应答协议消息处理
     *
     * @param message
     */
    public static void deviceResponseMsgHandler(String message) {
        MqttBaseRequest mqttBaseRequest = JSON.parseObject(message, MqttBaseRequest.class);
        String src = mqttBaseRequest.getSrc();
        String method = mqttBaseRequest.getMethod();
        long seq = mqttBaseRequest.getSeq();
        LockUtil.getInstance().unlock(src + method + seq, message);
    }

    /**
     * 判断是否为应答消息，如果为应答消息，则直接将消息设置到锁参数中，并解锁即可。
     *
     * @param msg
     * @return
     */
    public static boolean isResponse(String msg) {
        boolean result = false;
        try {
            JSONObject object = JSON.parseObject(msg);
            if (object.containsKey("result")) {
                result = true;
            }
        } catch (Exception e) {
            LOGGER.error("判断是否为应答数据，json解析异常 。", e);
        }
        return result;
    }

}
